$(document).ready(function(){
	
	selectStepClass(4);//选中导航菜单
	
	window.tdsort = 0;
	window.isSub = true;
	
	//置顶
	$(window).scroll(function () {
		if($(this).scrollTop()>$(window).height()){
			$(".srollbar-up-btn").show();
		}else{
			$(".srollbar-up-btn").hide();
		}
	});
	$('.srollbar-up-btn').bind('click', function(){
		$('body,html').animate({scrollTop: 0}, 'fast');
	});
	
	// 全局调用ajax 控制 防止 提交并发
	$("#stepconte-ul").ajaxComplete(function(event,request, settings){
		isSub = true;
	});
	
	
	initPage();
	
   // 绑定新增事件
   $("#createLecture-div-a").bind("click",function(){
	   initMeetCourse(null);
   });
	
	// 页面列表初始化
	function initPage(){
		$.ajax({
		   type: "POST",
		   url: basePath + "/course/fiveStep/getMeetCourseList",
		   data: "courseId="+$("#courseId").val(),
		   success: function(date){
			   if (!date.success){
				   //console.log("数据加载异常！");
				   return;
			   }
			   
			   if (date.result.length == 0){
				   // 初始化模板
				   initMeetCourse(null);
				   return;
			   }
			   
			   // 循环加载列表
			   for(i = 0 ;i <date.result.length; i++ ) {
				   initMeetCourse(date.result[i]);
			   }
		   },
		   error: function (XMLHttpRequest, textStatus, errorThrown) {
//               alert(XMLHttpRequest.status + ":" + XMLHttpRequest.statusText);
           }
		});
	}
	
	// 加载见面课数据列表和其各种事件
	function initMeetCourse(meetCourse) {
		
		var meetCourseId;
		if (meetCourse == null) {
			
			// font[name='sort'] 获取最后一个的id
			var arr = new Array();
			var i = 0;
	     	$("font[name='sort']").each(function(){
	     		arr[i] = this.parentNode.parentNode.id;
	     		i++;
			});
	     	
	     	// 如果上个见面课页面是关闭的 不需要调用 隐藏见面课编辑框操作
	     	if (arr[arr.length-1] != null && arr[arr.length-1] != '' && arr[arr.length-1] != 'null' && arr[arr.length-1] != 'undefined'){
	     		if ($('#spanrow'+arr[arr.length-1].substr(4,arr[arr.length-1].length)).attr("class") != 'uparrow downarrow'){
	     			hideMeetEditFrom(arr[arr.length-1].substr(4,arr[arr.length-1].length));
	        	}
	    	}
			
			meetCourseId = new Date().getTime()+"X";
		} else {
			meetCourseId = meetCourse.meetCourseId; // 存在对象
		}
		
		tdsort = tdsort + 1;
		// 创建新见面课 默认打开
    	var lecturePage = '<li name="lecture" id="Lectureli'+meetCourseId+'"> <input type="hidden" id="meetId_'+meetCourseId+'" value="'+meetCourseId+'">'
        	+ '<div class="icotit_div"><span class="hintico" id="mark'+meetCourseId+'"></span></div>'
            + '<div class="coursetitle">'
            + '<div class="faceLecture-div">'
            + '<div class="faceLecture-title clearfix" id="span'+meetCourseId+'">'
            + '<span class="fl">'+zLocale.fourstep_jianmianke+'：'+'<font id="fl'+meetCourseId+'" name="sort">' + tdsort + '</font></span>'        	
            + '<span class="uparrow" id="spanrow'+meetCourseId+'"></span>'
            + ' </div>'
            + '<span class="faceLecturedeleteico" id="removeLec'+meetCourseId+'" ></span>'            
            + '</div>'        
            + '<div class="faceLecture-content" id="LectureModel'+meetCourseId+'">'    
            + '<ul>'    
            + '<li>'    	
            + '<p>'+zLocale.fourstep_zhuti+'</p>'        	
            + '<div class="themediv">'            	
            + '<input type="text" placeholder="" maxlength="120" class="getFocus fl" data-tags="" value="" id="courseTopic'+meetCourseId+'" />'              
            + '<span class="wordlimit fr" id="word'+meetCourseId+'">120</span>'                	
            + '</div>'                    
            + '</li>'                 
            + '<li>'            
			+ '<p>'+zLocale.fourstep_jiaoxuemoshi+'</p>'			
            + '<div class="teachingmodel-div">'            	
            + '<select name="" id="taskType'+meetCourseId+'">'
            + '<option value ="">'+zLocale.fourthstep_please_choose_mode+'</option>'	
			+ '<option value ="5">'+zLocale.fourstep_zhibohudongke+'</option>'					
			+ '<option value ="8">'+zLocale.fourstep_zhongguojizhongmianshou+'</option>'		
			+ '<option value ="9">'+zLocale.fourstep_faguojizhongmianshou+'</option>'		
			+ '</select>'					
			+ '</div>'					
			+ '</li>'				
            + '<li>'            
			+ '<p class="clearfix"><span class="fl">'+zLocale.fourstep_jiaoxueyaoqiu+'</span><span class="questionmark-ico fl" id="demo-tip-yellowsimple'+meetCourseId+'" title="'+zLocale.fourstep_jiaoxueyaoqiutishi+'"></span></p>'			
            + '<div class="teachingmodel-div">'            	
            + '<div class="prerequisite_text getFocus" id="teachRequire'+meetCourseId+'" sname="ue" teachRequire=""></div>'                
			+ '</div>'					
			+ '</li>'				
            + '<li>'            
            + '<p>'+zLocale.fourstep_zhujiangren+'</p>'            
            + '<div class="teachingrequirements-div">'            	
            + '<input type="text" placeholder="" value="" class="institution_input getFocus" maxlength="50" data-tags="" name="" id="speakerStr'+meetCourseId+'" />'
            + '</div>'                   
			+ '</li>'				
            + '<li>'            
            + '<a href="javascript:void(0);" class="Savebtn mr10" id ="save'+meetCourseId+'">'+zLocale.fourstep_baocun+'</a>'            
            + '</li>'                
			+ '</ul>'			
            + '</div>'        
            + '</div>'    
            + '</li>';
    	$("#createLecture").before(lecturePage);
    	
    	
    	if (meetCourse != null) {
    		// 设置页面值
        	$("#courseTopic"+meetCourseId).val(meetCourse.courseTopic == null ? '' : meetCourse.courseTopic);
        	$("#teachRequire"+meetCourseId).attr("teachRequire",meetCourse.speakerName == null ? '' : meetCourse.speakerName);
        	$("#speakerStr"+meetCourseId).val(meetCourse.speakerName == null ? '' : meetCourse.speakerName);
        	
        	// 设置指定下拉为选中状态
        	if (meetCourse.taskType != null) {
            	$("#taskType"+meetCourseId).find("option[value='"+meetCourse.taskType+"']").attr("selected",true);
        	} else {
        		$("#taskType"+meetCourseId).find("option[value='']").attr("selected",true);
        	}
        	 
        	// 初始化标题长度
        	var course_title = $.trim($("#courseTopic" + meetCourseId).val());
    		var len ;// 记录长度
    		if(course_title.length > 120){
    			$("#word" + meetCourseId).val(course_title.substr(0,120));
    			len = 0;
    		} else {
    			len = 120 - course_title.length;
    		}
    		$("#word" + meetCourseId).html(len);
    	}
		
		// 初始化 tip
		$('#demo-tip-yellowsimple' + meetCourseId).poshytip({
			className: 'questionmarksimple',
			showTimeout: 1,
			alignTo: 'target',
			alignX: 'right',
			offsetY: -55,
			offsetX: 10,
			alignY: 'center',
			allowTipHover: false
		});
    	
    	// 加载百度编辑器
    	var ue = newEditor("teachRequire"+meetCourseId,886,50);
    	
    	var ueValue = "";
    	
    	if (meetCourse != null && meetCourse.teachRequire != null) {
    		ueValue = meetCourse.teachRequire;
    	} 
    	
    	loadEditorText(ue,ueValue);
		
		ue.addListener("blur", function (type, event) {
			
			// 设置值给指定自定义属性
			$("#teachRequire"+meetCourseId).attr("teachRequire",plainTxt(ue));
			
			// 检查完整度
        	if (isIntegrity()) {
   			 	 $("#mark"+meetCourseId).attr("class","rightico"); // 感叹号变成勾
	   		} else {
	   			 $("#mark"+meetCourseId).attr("class","hintico"); // 勾变成感叹号
	   		}
			
//        	console.log($("#meetId_"+meetCourseId).val());
			// 清空课程进度redis
			cleanTreeRedis($.trim($("#courseId").val()));
			meetCourseId = meetCourseId + "";
			var param = {"meetCourseId":($("#meetId_"+meetCourseId).val().charAt(meetCourseId.length-1) == "X" ? '' : $("#meetId_"+meetCourseId).val()),"courseId":$("#courseId").val(),'teachRequire':plainTxt(ue)};
//			console.log(param);
			if (isSub) { 
				isSub = false;
				$.ajax({
	    		   type: "POST",
	    		   url: basePath + "/course/fourStep/saveOrUpdate",
	    		   data: param,
	    		   success: function(data){
	    			   
	    			   if (!data.success){
	    				  //console.log("数据加载异常！");
	    				   return;
	    			   }
	    			   
	    			   if (meetCourseId.charAt(meetCourseId.length-1) == "X"){
//	    				   console.log(data.result.meetCourseId);
	    				   $("#meetId_"+meetCourseId).val(data.result.meetCourseId); // 设置id
	    			   }
	    			   
	    		   }
	    		});
			}
			
		});
		
		// 判断完整度
		function isIntegrity(){
			
			var courseTopic =  $.trim($("#courseTopic"+meetCourseId).val());
			if (courseTopic == null || courseTopic == '' || courseTopic == 'null' || courseTopic == 'undefined'){
	    		return false;
	    	}
			
			var taskType = $.trim($("#taskType"+meetCourseId).val());
			if (taskType == null || taskType == '' || taskType == 'null' || taskType == 'undefined'){
	    		return false;
	    	}
			
			var speakerStr = $.trim($("#speakerStr"+meetCourseId).val());
			if (speakerStr == null || speakerStr == '' || speakerStr == 'null' || speakerStr == 'undefined'){
	    		return false;
	    	}
			
			var teachRequire = $("#teachRequire"+meetCourseId).attr("teachRequire");
			if (teachRequire == null || teachRequire == '' || teachRequire == 'null' || teachRequire == 'undefined'){
	    		return false;
	    	}
			return true;
		}
		
		if (isIntegrity()) {
			 $("#mark"+meetCourseId).attr("class","rightico"); // 感叹号变成勾
		} else {
			 $("#mark"+meetCourseId).attr("class","hintico"); // 勾变成感叹号
		}
		
		// 绑定  记录见面课长度事件
		$("#courseTopic" + meetCourseId).bind("keyup",function(){
			var course_title = $.trim($("#courseTopic" + meetCourseId).val());
			var len ;// 记录长度
			if(course_title.length > 120){
				$("#word" + meetCourseId).val(course_title.substr(0,120));
				len = 0;
			} else {
				len = 120 - course_title.length;
			}
			$("#word" + meetCourseId).html(len);
    	});	
		
		// 显示隐藏见面课编辑框
		function hideMeetEditFrom(meetCourseId){
			if(!$("#LectureModel"+meetCourseId).is(":animated")){ 
	   			 //********问题点在这里，这里有判断是否处于动画
	   	       	 $("#LectureModel"+meetCourseId).slideToggle("slow");
	   	       	 $('#spanrow'+meetCourseId).toggleClass("downarrow");
			}
			return false;
		}
		
		// 请求接口
    	function editPost(meetCourseId,column){
    		
    		// 检查完整度
        	if (isIntegrity()) {
   			 	 $("#mark"+meetCourseId).attr("class","rightico"); // 感叹号变成勾
	   		} else {
	   			 $("#mark"+meetCourseId).attr("class","hintico"); // 勾变成感叹号
	   		}
    		
    		// 清空课程进度redis
    		cleanTreeRedis($.trim($("#courseId").val()));
    		
//    		console.log($("#meetId_"+meetCourseId).val());
    		meetCourseId = meetCourseId + "";
    		var param = {"meetCourseId":($("#meetId_"+meetCourseId).val().charAt(meetCourseId.length-1) == "X" ? '' : $("#meetId_"+meetCourseId).val()),'courseId':$("#courseId").val()};
        	
        	param[column] = $.trim($("#" + column + meetCourseId).val());
        	
//        	console.log(param);
        	if (isSub) {
        		isSub = false;
        		$.ajax({
          		   type: "POST",
          		   url: basePath + "/course/fourStep/saveOrUpdate",
          		   data: param,
          		   success: function(data){
          			  if (!data.success){
          				 return;
          			  }
          			  
          			  if (meetCourseId.charAt(meetCourseId.length-1) == "X"){
//          				console.log(data.result.meetCourseId);
          				 $("#meetId_"+meetCourseId).val(data.result.meetCourseId); // 设置id
       			      }
          		   }
          		});
        	}
        	
    	}
		
    	// 展开收起事件
    	$("#span" + meetCourseId).bind("click",function(){
    		hideMeetEditFrom(meetCourseId);
    	});
    	
    	// 保存收起事件
    	$("#save" + meetCourseId).bind("click",function(){
    		hideMeetEditFrom(meetCourseId);
    	});
    	
    	// 绑定编辑见面课名称事件
    	$("#courseTopic" + meetCourseId).bind("blur",function(){
    		editPost(meetCourseId,"courseTopic");
    	});
    	
    	// 绑定选择课程下拉事件
    	$("#taskType" + meetCourseId).bind("change",function(){
    		editPost(meetCourseId,"taskType");
    	});
    	
    	// 绑定编辑讲师的事件
    	$("#speakerStr" + meetCourseId).bind("blur",function(){
    		editPost(meetCourseId,"speakerStr");
    	});
    	
    	// 绑定删除事件
    	$("#removeLec" + meetCourseId).bind("click",function(){
    		
    		layer.confirm(zLocale.public_message, {
    			title:' ', 
	    	    skin: 'layui-layer-zhs',
	    	    icon:0,
	    	    shade:.6,
	    	    btn: [zLocale.public_confim,zLocale.public_cancel] //按钮
	    	 }, function(){
	    		 
	    		 	var meetId = $("#meetId_" + meetCourseId).val();
	    		 
	    		 	// 执行删除操作
	    	      	$("#Lectureli"+ meetCourseId).remove(); 
	    	     	 
	    	      	var i = 0;
	    	    	// 重新排序
	    	     	$("font[name='sort']").each(function(){
	    	     		i = i + 1;
	    	     		$("#" + this.id).html(i);
	    			});
	    	     	
	    	     	tdsort = tdsort - 1;
	    	     	
	    	     	if (meetId.charAt(meetCourseId.length-1) == "X"){
	    				layer.msg({
	    		    	     time: 1000, //1s后自动关闭
	    		    	   });
	    	    		return;
	    			} 
	    	     	
	    	    	// 清空课程进度redis
	    			cleanTreeRedis($.trim($("#courseId").val()));
	    	    	
	    			var param = {"meetCourseId":meetId,'courseId':$("#courseId").val()};
	    			
	    			if (isSub) { 
	    				isSub = false;
	    				//系统业务处理
		    	    	$.ajax({
		    	   		   type: "POST",
		    	   		   url: basePath + "/course/fourStep/remove",
		    	   		   data: param,
		    	   		   success: function(data){
		    	   			 if (!data.success){
		    	   				 return;
		    				 }
		    	   			 layer.msg({
		    	 	    	     time: 1000, //1s后自动关闭
		    	 	    	   });
		    	   		   }
		    	   		});
	    			}
	    			
	    	 }, function(){
	    		 // 取消不做操作
	    	 });
    	});
    	
	}
});	
	
    